/**********************************************************************
Compile : gcc -O3 -o draw draw.c -lgd
Usage : (./draw N L size color_low color_high inputfile outputfile
      : For example: ./draw 11 12 64 0 255 Yeast.txt Yeast.png
**********************************************************************/

#include <gd.h>
#include <stdlib.h>
#include <unistd.h>

void print_help ()
{
	printf ("Usage         : ./draw N L size color_low colow_high inputfile outputfile\n");
	printf ("                (./draw 11 12 64 0 255 Yeast.txt Yeast.png)\n");
	printf ("N             : number of the nodes\n");
	printf ("L             : number of the steps\n");
	printf ("size          : number of pixels for each cell\n");
	printf ("color_low     : color value (8-bit grayscale) responding to \"1\" in the process\n");
	printf ("color_high    : color value (8-bit grayscale) responding to \"0\" in the process\n");
}

int main (int argc, char *argv[])
{
	gdImagePtr im;
	FILE *fp;
	char buf[256];
	int N, L, size, low, high;

	if (argc == 1)
	{
		print_help ();
		exit (0);
	}

	N = atoi (argv[1]);
	L = atoi (argv[2]);
	size = atoi (argv[3]);
	low = atoi (argv[4]);
	high = atoi (argv[5]);

	int i, j, n, color;
	int pathway[L][N];
	float process[L][N];

	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			process[i][j] = 0.0;
		}
	}

	n = 0;
	fp = fopen (argv[6], "r");
	while (fgets (buf, 256, fp))
	{
		for (i = 0; i < L; i++)
		{
			for (j = 0; j < N; j++)
			{
				fscanf (fp, "%d", &(pathway[i][j]));
				process[i][j] += pathway[i][j];
			}
			fgets (buf, 256, fp);
		}

		n ++;
	}
	fclose (fp);

	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			process[i][j] /= n;
		}
	}

	im = gdImageCreate (N * size, L * size);

	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			color = low + (high - low) * (1.000 - process[i][j]);
			color = gdImageColorAllocate (im, color, color, color);
			gdImageFilledRectangle (im, j * size, i * size, (j + 1) * size - 1, (i + 1) * size - 1, color);
		}
	}

	/*
	color = gdImageColorAllocate (im, 255, 255, 255);
	gdImageFilledRectangle (im, N * size, 0, (N + 1) * size - 1, L * size - 1, color);

	for (i = low; i <= high; i++)
	{
		color = gdImageColorAllocate (im, i, i, i);
		gdImageFilledRectangle (im, (N + 1) * size, (i - low) * L * size / (high - low + 1), (N + 2) * size - 1, (i + 1 - low) * L * size / (high - low + 1) - 1, color);
	}
	*/

	fp = fopen (argv[7], "wb");
	gdImagePng (im, fp);
	fclose (fp);

	gdImageDestroy (im);

	exit (0);
}
